import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../services/database_service.dart';
import 'dart:async';
import 'package:uuid/uuid.dart';
import 'circular_countdown.dart';
import 'long_press_circle_button.dart';
/// 俯卧撑训练页面
class PushUpScreen extends StatefulWidget {
  const PushUpScreen({Key? key}) : super(key: key);

  @override
  State<PushUpScreen> createState() => _PushUpScreenState();
}

class _PushUpScreenState extends State<PushUpScreen> {
  int groupCount = 0;
  bool training = true;
  final player = AudioPlayer();
  final dbService = DatabaseService();
  bool _showRest = false;
  int? _intervalHours;
  int _restTimeSeconds = 60; // 默认60秒组间休息

  @override
  void initState() {
    super.initState();
    _loadTodayRecord();
    _loadLastRecordInterval();
    _loadRestTimeSetting();
  }

  Future<void> _loadRestTimeSetting() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _restTimeSeconds = prefs.getInt('sport_rest_time') ?? 60;
    });
  }

  Future<void> _loadTodayRecord() async {
    final today = DateTime.now().toIso8601String().substring(0, 10);
    final record = await dbService.getSportRecordByDate(today, '俯卧撑');
    if (record != null) {
      setState(() {
        groupCount = record['count'] ?? 0;
      });
    }
  }

  Future<void> _loadLastRecordInterval() async {
    final last = await dbService.getLastSportRecordBeforeToday('俯卧撑');
    if (last != null) {
      final lastDate = DateTime.parse(last['createdAt']);
      final now = DateTime.now();
      final diff = now.difference(lastDate).inHours;
      if (diff < 48) {
        setState(() {
          _intervalHours = diff;
        });
      } else {
        setState(() {
          _intervalHours = null;
        });
      }
    } else {
      setState(() {
        _intervalHours = null;
      });
    }
  }

  Future<void> _showRestDialog() async {
    setState(() => _showRest = true);
    await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return AlertDialog(
          title: Text('组间休息 ($_restTimeSeconds秒)'),
          content: CircularCountdown(
            seconds: _restTimeSeconds,
            color: Colors.blue,
            onFinish: () async {
              Navigator.of(context).pop();
              await player.play(AssetSource('audio/done.mp3'));
            },
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                player.play(AssetSource('audio/done.mp3'));
              },
              child: const Text('跳过'),
            ),
          ],
        );
      },
    );
    setState(() => _showRest = false);
  }

  Future<bool> _onWillPop() async {
    if (training) {
      return await showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: const Text('提示'),
              content: const Text('训练尚未结束，确定要退出吗？'),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () => Navigator.of(context).pop(true),
                  child: const Text('确定'),
                ),
              ],
            ),
          ) ??
          false;
    }
    return true;
  }

  void _recordGroup() async {
    setState(() {
      groupCount++;
    });
    await _showRestDialog();
  }

  void _finishTraining() async {
    setState(() {
      training = false;
    });
    await dbService.saveSportRecord(
      id: const Uuid().v4(),
      date: DateTime.now().toIso8601String().substring(0, 10),
      type: '俯卧撑',
      count: groupCount,
      duration: 0,
    );
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        appBar: AppBar(title: const Text('俯卧撑训练')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              SizedBox(height: 30),
              if (_intervalHours != null)
                Padding(
                  padding: const EdgeInsets.only(bottom: 8.0),
                  child: Text('距离上次训练：$_intervalHours 小时',
                      style: const TextStyle(color: Colors.red, fontSize: 16)),
                ),
              Text('已完成组数', style: Theme.of(context).textTheme.titleLarge),
              const SizedBox(height: 8),
              Text('$groupCount',
                  style: const TextStyle(
                      fontSize: 48, fontWeight: FontWeight.bold)),
              const SizedBox(height: 32),
              GestureDetector(
                onTap: _recordGroup,
                child: Container(
                  width: 120,
                  height: 120,
                  decoration: const BoxDecoration(
                    color: Colors.blue,
                    shape: BoxShape.circle,
                  ),
                  alignment: Alignment.center,
                  child: const Text('训练完成\n记录一组',
                      style: TextStyle(color: Colors.white, fontSize: 20)),
                ),
              ),
              const SizedBox(height: 32),
              LongPressCircleButton(
                onLongPress: _finishTraining,
                color: Colors.red,
                text: '长按结束',
                size: 120,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
